﻿Public Class FileChecker

    Public Shared Function CheckSignature(ByVal filePath As String, ByVal signatureSize As Integer, ByVal expectedSignature As String) As Boolean
        If String.IsNullOrEmpty(filePath) Then Throw New ArgumentException("You must specify a filepath.")
        If String.IsNullOrEmpty(expectedSignature) Then Throw New ArgumentException("Must specify a value for the expected file signature")
        CheckSignature = False
        Using fs As New System.IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite)
            If fs.Length < signatureSize Then Exit Function
            Dim signature() As Byte
            ReDim signature(signatureSize)
            Dim bytesRequired As Integer = signatureSize
            Dim index As Integer = 0
            While bytesRequired > 0
                Dim bytesRead As Integer = fs.Read(signature, index, bytesRequired)
                bytesRequired = bytesRequired - bytesRead
                index += bytesRead
            End While
            Dim actualSignature As String = BitConverter.ToString(signature)
            If String.Compare(actualSignature, expectedSignature) = 0 Then CheckSignature = True
            fs.Close()
            fs.Dispose()
        End Using
    End Function


    Public Shared Function GetSignature(ByVal filePath As String, ByVal signatureSize As Integer) As String
        GetSignature = ""
        If String.IsNullOrEmpty(filePath) Then Throw New ArgumentException("You must specify a filepath.")
        Using fs As New System.IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite)
            If fs.Length < signatureSize Then Exit Function
            Dim signature() As Byte
            ReDim signature(signatureSize)
            Dim bytesRequired As Integer = signatureSize
            Dim index As Integer = 0
            While bytesRequired > 0
                Dim bytesRead As Integer = fs.Read(signature, index, bytesRequired)
                bytesRequired = bytesRequired - bytesRead
                index += bytesRead
            End While
            GetSignature = BitConverter.ToString(signature)

            fs.Close()
            fs.Dispose()
        End Using
    End Function
    
End Class

